package com.applcn.message.utils.email;

import com.applcn.message.apollo.EmailConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

/**
 * com.applcn.message.utils.email
 * Description:
 *
 * @author: 大妖怪
 * @date: 2020-02-14 16:48
 */
@Component
@RequiredArgsConstructor
public class SmtpUtil {
    private final EmailConfig config;
    private static final String protocol = "smtp";
    private static Session session;

    @PostConstruct
    public void init() {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", protocol);
        properties.put("mail.smtp.host", config.getHost());
        properties.put("mail.smtp.port", config.getPort());
        properties.put("mail.smtp.auth", config.getAuth());
        properties.put("mail.debug", config.getDebug());
        session = Session.getInstance(properties);
    }

    /**
     * 发送文字邮件
     *
     * @param receiveAccount 收件人邮箱
     * @param title          邮件标题
     * @param content        邮件内容
     * @throws MessagingException
     */
    public void sendTextEmail(String receiveAccount, String title, String content)
            throws MessagingException {

        // 创建新邮件
        MimeMessage mimeMessage = new MimeMessage(session);
        // 设置发件人
        mimeMessage.setFrom(new InternetAddress(config.getAccount()));
        // 设置收件人
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveAccount));
        // 设置标题
        mimeMessage.setSubject(title);
        // 设置正文
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(content, "text/html;charset=UTF-8");
        // 描述数据关系
        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(text);
        // 使用related类型，邮件中除了可以携带各种附件外，还可以将其它内容以内嵌资源的方式存储在邮件中
        mimeMultipart.setSubType("related");
        mimeMessage.setContent(mimeMultipart);
        mimeMessage.saveChanges();

        // 发送邮件
        Transport transport = session.getTransport();
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();
    }

}
